import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/cookie")
public class CookieServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 从客户端请求中读取 Cookie
        Cookie[] cookies = request.getCookies();

        // 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");

        // 获取响应对象的 PrintWriter
        PrintWriter out = response.getWriter();

        // 输出请求中的 Cookie 到响应中
        out.println("<html>");
        out.println("<head><title>Cookie Information</title></head>");
        out.println("<body>");
        out.println("<h1>Cookie Information</h1>");

        if (cookies != null) {
            out.println("<p>Client's Cookies:</p>");
            for (Cookie cookie : cookies) {
                out.println("<p>" + cookie.getName() + ": " + cookie.getValue() + "</p>");
            }
        } else {
            out.println("<p>No Cookies from the client.</p>");
        }

        // 向客户端写入自定义 Cookie 对象
        Cookie customCookie = new Cookie("customCookie", "Hello from CookieServlet!");
        customCookie.setMaxAge(60 * 60 * 24 * 30); // 设置为持久 Cookie，有效期为30天
        response.addCookie(customCookie);

        out.println("<p>Custom Cookie has been set on the response.</p>");
        out.println("</body>");
        out.println("</html>");
    }
}
